package cn.zl.netty.work;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Description:聊天服务器的处理器
 * @Author: zllwsy
 * @Date: 2020/10/29 9:42
 */
public class MyChatServerHandler extends SimpleChannelInboundHandler<Object> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static final String SEPARATOR = System.lineSeparator();


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("MyChatServerHandler.handlerAdded");
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        channelGroup.writeAndFlush("Server>" + channel.remoteAddress() + "add" + SEPARATOR + "收到了\n");
        msg = "ss";
        ctx.writeAndFlush(msg);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception{
        System.out.println("MyChatServerHandler.channelACTIVE");
        System.out.println("client" + ctx.channel().remoteAddress() + "处于连接状态");
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx,Object msg) throws Exception{
        System.out.println("Server: " + ctx);
        Channel channel = ctx.channel();
        System.out.println("===========|客户端发来的消息: " + channel.remoteAddress() + "> " + msg);

        for (Channel ch : channelGroup) {
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + "> " + msg + SEPARATOR);
            } else {
                ch.writeAndFlush("自己" + "> " + msg + SEPARATOR);
            }
        }
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.channelInactive");
        System.out.println("client" + ctx.channel().remoteAddress() + "处于断开状态");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyChatServerHandler.handlerRemoved");

        Channel channel = ctx.channel();
        channelGroup.remove(channel); // Netty会自动寻找断掉的channel，然后移除，可以不用手动移除
        channelGroup.writeAndFlush("Server> " + channel.remoteAddress() + " remove" + SEPARATOR);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
